package android.tusnotas.core;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.XPatherException;

import android.tusnotas.parser.folders.FoldersParser;
import android.tusnotas.beans.Folder;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.util.Devel;
import android.util.Log;

public class FoldersAndFilesAnalyser {

	private WebServiceCaller caller = new WebServiceCaller();
	
	private int ttt = 5;//times to try before giving up connection try

	public List<Folder> doGetFoldersAndFiles(String aulaID) throws RemoteReadingException, ProcessingInstancesException{
		String XML = doGetRemoteMoreInfoCouse(aulaID);
		List<Folder> folders = doObtainFolders(XML);
		return folders;
	}
	
	private List<Folder> doObtainFolders(String XML) throws ProcessingInstancesException{
		List<Folder> folders = null;
		
		FoldersParser foldersParser = new FoldersParser();
		
		try {
			folders = foldersParser.parseXML(XML);
		} catch (XPatherException e) {
			e.printStackTrace();
			throw new ProcessingInstancesException();
		}
		if(folders == null){
			folders = new ArrayList<Folder>();
		}
		return folders;
	}
	
	private String doGetRemoteMoreInfoCouse(String aulaID) throws RemoteReadingException{

		String XML="";

		try {
			caller.SetForMoreInfoCouse(aulaID);
			XML = persistentCaller();
		} catch (RemoteReadingException rwce) {
			//TODO CATCH IT AN THROW IT, JUST IN CASE WE NEED TO DO SOMETHING ABOUT IT
			throw rwce;
		} catch (Exception e){
			if( Devel.fullDevel){
				Log.w(this.getClass().getName(), "ERROR WHILE CONNECTING TO WC");
			}
			RemoteReadingException rwce = new RemoteReadingException();
			rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
			throw rwce;
		}

		return XML;
	}
	
	private String persistentCaller() throws RemoteReadingException{	
		while( ttt > 0){
			try{
				String XML = caller.execute();
				return XML;
			}catch(RemoteReadingException e){}
			ttt--;
		}
		throw new RemoteReadingException();

	}

}
